<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="face-box">
    <video id="video"></video>
    <canvas id="canvas" style="display: none;"></canvas>
</div>


<script>
    var video = document.getElementById('video');
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    function getUserMediaToPhoto(constraints,success,error) {
        if(navigator.mediaDevices.getUserMedia){
            //最新标准API
            navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
        }else if (navigator.webkitGetUserMedia) {
            //webkit核心浏览器
            navigator.webkitGetUserMedia(constraints,success,error);
        }else if(navigator.mozGetUserMedia){
            //firefox浏览器
            navigator.mozGetUserMedia(constraints,success,error);
        }else if(navigator.getUserMedia){
            //旧版API
            navigator.getUserMedia(constraints,success,error);
        }
    }
    //成功回调函数
    function success(stream){
        //兼容webkit核心浏览器
        var CompatibleURL = window.URL || window.webkitURL;
        //将视频流转化为video的源
        video.src = CompatibleURL.createObjectURL(stream);
        video.play();//播放视频
        //将视频绘制到canvas上
        postFace()
    }
    function error(error) {
        console.log('访问用户媒体失败：',error.name,error.message);
    }
    function postFace() {
        setTimeout(function () {
            context.drawImage(video,0,0,480,320);
            img=canvas.toDataURL('image/jpg')
            // img=img.split(',')[1]
            //将照片以base64用ajax传到后台
            $.post({
                url:'http://test.xiaoyang666.top/login/faceLogin.do',
                data:{
                    message:img
                },
                success:function (data) {
                   alert(data)
                },
                error:function (callback) {
                    postFace()
                }
            })
        },300)
    }
    if(navigator.mediaDevices.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia){
        getUserMediaToPhoto({video:{width:480,height:320}},success,error);
    }else{
        alert('你的浏览器不支持访问用户媒体设备');
    }
</script>

</body>
</html>